package com.xiaogao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaogao.common.entity.PageData;
import com.xiaogao.common.utils.ip.IpUtils;
import com.xiaogao.sys.mapper.SysLogLoginMapper;
import com.xiaogao.sys.model.SysLogLogin;
import com.xiaogao.sys.request.log.login.QueryParam;
import com.xiaogao.sys.response.SysLogLoginResponse;
import com.xiaogao.sys.service.SysLogLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

@Service
@Slf4j
public class SysLogLoginServiceImpl extends ServiceImpl<SysLogLoginMapper, SysLogLogin> implements SysLogLoginService {
    @Autowired
    @Qualifier("logLoginExecutor")  // 指定使用登录日志线程池
    private ExecutorService logLoginExecutor;

    @Autowired
    private SysLogLoginMapper sysLogLoginMapper;

    @Override
    public void insert(String id) {
        CompletableFuture.runAsync(() -> {
            // 登录日志处理逻辑
            SysLogLogin sysLogLogin = new SysLogLogin();
            sysLogLogin.setUserId(id);
            sysLogLogin.setCreateTime(LocalDateTime.now());
            sysLogLogin.setHost(IpUtils.getClientIp());
            sysLogLoginMapper.insert(sysLogLogin);
        }, logLoginExecutor);
    }

    @Override
    public PageData<SysLogLoginResponse> querySelective(Integer pageNum, Integer pageSize, QueryParam queryParam) {
        // limit offset,pageSize    ---> offset = (pageNum - 1) * pageNum
        Integer offset = (pageNum - 1) * pageNum;
        List<SysLogLoginResponse> list = sysLogLoginMapper.querySelective(offset,pageSize,queryParam);

        LambdaQueryWrapper<SysLogLogin> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(queryParam.getHost()),SysLogLogin::getHost,queryParam.getHost());
        wrapper.eq(StringUtils.isNotEmpty(queryParam.getUserId()),SysLogLogin::getUserId,queryParam.getUserId());
        if (queryParam.getRangeTime() != null && queryParam.getRangeTime().size() == 2) {
            wrapper.ge(SysLogLogin::getCreateTime, queryParam.getRangeTime().get(0));  // >= 开始时间
            wrapper.le(SysLogLogin::getCreateTime, queryParam.getRangeTime().get(1));  // <= 结束时间
        }
        Long total = sysLogLoginMapper.selectCount(wrapper);
        return new PageData<>(list,total);
    }

    @Override
    public void delete(List<String> ids) {
        if(CollectionUtils.isNotEmpty(ids)){
            sysLogLoginMapper.deleteByIds(ids);
        }
    }
}
